package servlet.user;

import static database.Config.properties;

import java.io.IOException;
import java.io.InputStream;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import managers.EntityFunctionManager;

import entities.Message;
import entities.User;

/**
 * Servlet implementation class ServletUserFunctions.Servlet generique
 * qui recoit tous les fonctions d'un utilisateur, selon besoin il appellera
 * aux methodes du manager
 */
public class ServletUserFunctions extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletUserFunctions() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String name = (String)request.getSession().getAttribute("id");
		String choise = request.getParameter("choise");
		if(choise.equals("addMess")) {
			System.out.println("addMess");
			addMessage(name, request, response);
		}
		if(choise.equals("listMess")) {
			System.out.println("listMess");
			showMessage(name, request,response);
		}
		if(choise.equals("changePho")){
			System.out.println("changePho");
			upImage(name,request,response);
		}
		if(choise.equals("showPho")) {
			System.out.println("not null");
			System.out.println("showPho");
			showImage(name, request,response);
		}
		if(choise.equals("modProf")) {
			System.out.println("modProf");
			modifInfo(name, request,response);
		}
		if(choise.equals("logOut")){
			logOut(request,response);
		}
	}
	
	/**
	 * Add message looks the user in the database, 
	 * then forwards the information to a page jsp, so we can add the message
	 */
	@EJB EntityFunctionManager mng;
	protected void addMessage(String name, HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
		/*if(!name.isEmpty()){
			//User user = mng.searchByName(name); 
			String user = (String) request.getAttribute("id");
			if(user == null) {
				String goTo="Error.jsp";
				request.getRequestDispatcher(goTo).forward(request, response);
			}
			else {
				String goTo="SendMessage.jsp";
				//String utilisateur = user.getUser();
				request.setAttribute("data", user);
				request.setAttribute("user", utilisateur);
				request.getRequestDispatcher(goTo).forward(request, response);
			}
		//}
		//else {
		//	String goTo="Error.jsp";
		//	request.getRequestDispatcher(goTo).forward(request, response);
		//}*/
	}
	
	/**
	 * List messages, gets the user from the session then 
	 * forwards the information to a page jsp
	 */
	
	protected void showMessage(String name, HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
		if(!name.isEmpty()){
			User user = mng.searchByName(name); 
			if(user == null) {
				String goTo="Error.jsp";
				request.getRequestDispatcher(goTo).forward(request, response);
			}
			else {
				List<Message> list = mng.listMessages(user.getUser());
				
				String goTo="MessageList.jsp";
				request.setAttribute("data", list);
				request.getRequestDispatcher(goTo).forward(request, response);
			}
		}
		else {
			String goTo="Error.jsp";
			request.getRequestDispatcher(goTo).forward(request, response);
		}
	}
	
	/**
	 * Add photo ask for the user to upload an image
	 */

	protected void upImage(String name, HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
		if(!name.isEmpty()) {
			String goTo="AddPhoto.jsp";
			//String myObjectId = UUID.randomUUID().toString();	
			request.getSession().setAttribute("myObjectId", name);
			request.getRequestDispatcher(goTo).forward(request, response);
		}
		else {
			String goTo="Error.jsp";
			request.getRequestDispatcher(goTo).forward(request, response);
		}

	}
	
	/**
	 * Show photo reads the session user and puts it's picture
	 */
	
	protected void showImage(String user, HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
		String connectionURL = properties.getProperty("dbURL");
		java.sql.Connection con=null;
		System.out.println("not null");
		try{
			Class.forName(properties.getProperty("driver")).newInstance();
			con=DriverManager.getConnection(connectionURL,properties.getProperty("username"),properties.getProperty("password"));
			Statement st1=con.createStatement();
			//String user = (String)request.getSession().getAttribute("id");
			System.out.println("not null");
			ResultSet rs1 = st1.executeQuery("select photo from User where user='"+user+"'");
			System.out.println(rs1+"not null");
			String imgLen="";
			if(rs1!=null) {
				if(rs1.next()){
					imgLen = rs1.getString(1);
					System.out.println(imgLen.length());
				}
				rs1 = st1.executeQuery("select photo from User where user='"+user+"'");
				if(rs1.next()){
					int len = imgLen.length();
					byte [] rb = new byte[len];
					InputStream readImg = rs1.getBinaryStream(1);
					int index=readImg.read(rb, 0, len);
					System.out.println("index"+index);
					st1.close();
					response.reset();
					response.setContentType("image/jpg");
					response.getOutputStream().write(rb,0,len);
					response.getOutputStream().flush();
				}
			}
			else{
				ResultSet rs2 = st1.executeQuery("select photo from User where user='default'");
				String imgLen2="";
				if(rs2!=null) {
					if(rs2.next()){
						imgLen2 = rs2.getString(1);
						System.out.println(imgLen2.length());
					}
					rs2 = st1.executeQuery("select photo from User where user='default'");
					if(rs2.next()){
						int len = imgLen2.length();
						byte [] rb = new byte[len];
						InputStream readImg = rs2.getBinaryStream(1);
						int index=readImg.read(rb, 0, len);
						System.out.println("index"+index);
						st1.close();
						response.reset();
						response.setContentType("image/jpg");
						response.getOutputStream().write(rb,0,len);
						response.getOutputStream().flush();
					}
				}
			}
		} catch (Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * Modify changes the user information.
	 */
	
	protected void modifInfo(String name, HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
		if(!name.isEmpty()){
			User user = mng.searchByName(name); 
			if(user == null) {
				String goTo="Error.jsp";
				request.getRequestDispatcher(goTo).forward(request, response);
			}
			else {
				String goTo="Modify_Champs.jsp";
				String utilisateur = user.getUser();
				request.setAttribute("data", user);
				request.setAttribute("user", utilisateur);
				request.getRequestDispatcher(goTo).forward(request, response);
			}
		}
		else {
			String goTo="Error.jsp";
			request.getRequestDispatcher(goTo).forward(request, response);
		}
	}
	
	/**
	 * We can log out of the system.
	 */
	protected void logOut(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException  {
		 try {
	            // on récupère la session ou on la crée si elle n'existe pas
	           // HttpSession session = request.getSession(true);
	            // on l'invalide et on revient sur la page d'accueil
	            request.getSession(false).invalidate();
	            //session.removeAttribute("id");
	            request.setAttribute("message","Logout successed");
	           
	            request.getRequestDispatcher("index.html").forward(request,response);
	        } catch (Exception e) {
	            request.setAttribute("error",e);
	            request.setAttribute("message","Logout failed");
	            request.getRequestDispatcher("index.html").forward(request,response);
	        }
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request,response);
	}

}
